package org.xnat.xnatfs.event;

import java.util.Map;

import org.apache.log4j.Logger;
import org.xnat.xnatfs.webdav.VirtualResource;

import com.bradmcevoy.http.EventListener;
import com.bradmcevoy.http.FileItem;
import com.bradmcevoy.http.Request;
import com.bradmcevoy.http.Resource;
import com.bradmcevoy.http.Response;

public class ResourceClosingEventListener implements EventListener {
  private static final Logger logger = Logger.getLogger ( ResourceClosingEventListener.class );

  @Override
  public void onGet ( Request request, Response response, Resource resource, Map<String, String> params ) {
    // no-op
  }

  @Override
  public void onPost ( Request request, Response response, Resource resource, Map<String, String> params, Map<String, FileItem> files ) {
    // no-op
  }

  /**
   * Ensure that the resource has been closed to prevent things like the
   * HttpStreamAssets from sticking around.
   */
  @Override
  public void onProcessResourceFinish ( Request request, Response response, Resource resource, long duration ) {
    if ( resource != null && resource instanceof VirtualResource ) {
      logger.debug ( "Closing asset " + resource.toString () );
      ( (VirtualResource) resource ).close ();
    }
  }

  @Override
  public void onProcessResourceStart ( Request request, Response response, Resource resource ) {
    // no-op
  }

}
